package com.pccw.sb.dubbo.dao.base;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.pccw.core.base.BaseEntity;

@Repository
@Transactional
public class CommonDao {

	@PersistenceContext
	private EntityManager entityManager;

	public <T extends BaseEntity> T get(Class<T> type, String id) {
		return entityManager.find(type, id);
	}

	public <T extends BaseEntity> T update(T entity) {
		return entityManager.merge(entity);
	}

	public <T extends BaseEntity> void save(T entity) {
		entityManager.persist(entity);
	}

	public <T extends BaseEntity> void delete(T entity) {
		entityManager.remove(entity);
	}

	@SuppressWarnings("rawtypes")
	public List getAll(Class<? extends BaseEntity> tableClass) {
		Query query = entityManager.createQuery("from " + tableClass.getSimpleName());
		return query.getResultList();
	}

}